package top.cyuw.simplerpc.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import top.cyuw.simplerpc.config.RpcServiceConfig;
import top.cyuw.simplerpc.proxy.RpcClientProxy;
import top.cyuw.simplerpc.remoting.client.SimpleRpcClient;
import top.cyuw.simplerpc.spring.annotation.RpcReference;

import java.lang.reflect.Field;

/**
 * @author chen
 * @date 2023/3/14 22:23
 */
public class RpcReferenceAnnotationPostProcessor implements BeanPostProcessor {

    private final SimpleRpcClient rpcClient;

    public RpcReferenceAnnotationPostProcessor(SimpleRpcClient rpcClient) {
        this.rpcClient = rpcClient;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            RpcReference rpcReference = field.getAnnotation(RpcReference.class);
            if (rpcReference != null) {
                RpcServiceConfig serviceConfig = RpcServiceConfig.builder().version(rpcReference.version()).group(rpcReference.group()).build();
                RpcClientProxy clientProxy = new RpcClientProxy(rpcClient, serviceConfig);
                Object proxy = clientProxy.getProxy(field.getType());
                boolean accessible = field.isAccessible();
                try {
                    field.setAccessible(true);
                    field.set(bean, proxy);
                } catch (IllegalAccessException ignored) {

                } finally {
                    field.setAccessible(accessible);
                }
            }
        }
        return bean;
    }

}
